﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace IndyMosaic.Core.Extensions
{
    public static class UrlExtensions
    {
        public static string GetRelativeUrl(this UrlHelper url, string applicationUrl)
        {
            string appPath = url.RequestContext.HttpContext.Request.ApplicationPath;
            string relativeUrl = string.Format("~/{0}", applicationUrl.Substring(appPath.Length));
            return relativeUrl;
        }

        public static string GetContentAbsoluteUrl(this UrlHelper url, string relativeUrl)
        {
            if (relativeUrl.StartsWith("~/"))
            {
                return  url.RequestContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority) + url.Content(relativeUrl);
            }

            Uri uri = new Uri(relativeUrl);
            if (!uri.IsAbsoluteUri)
            {
                string first = url.RequestContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority);
                if (!relativeUrl.StartsWith(url.RequestContext.HttpContext.Request.ApplicationPath))
                {
                    first += url.RequestContext.HttpContext.Request.ApplicationPath;
                }
                return first + relativeUrl;
            }
            else
            {
                return relativeUrl;
            }
        }
    }
}
